package com.joe.demo.nio.buffer;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @Description 粘包 半包
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class TestByteBufferExam {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("Hello,word\nI'm zhangsan\nHo".getBytes(StandardCharsets.UTF_8));
        split(buffer);
        buffer.put("w are you?\n".getBytes(StandardCharsets.UTF_8));
        split(buffer);
    }

    private static void split(ByteBuffer buffer){
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            // 找到一条完整消息
            if (buffer.get(i) == '\n') {
                //存入新的 ByteBuffer
                int length = i + 1 - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    byte b = buffer.get();
                    log.info("字符：{}", (char) b);
                    target.put(b);
                }
                target.flip();
                log.info("消息: {}", StandardCharsets.UTF_8.decode(target));
            }
        }
        buffer.compact();
    }
}
